from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from home import models, ser
from django.core.cache import cache
from home.tasks import send_mail



# Create your views here.


class NavList(APIView):
    def get(self, request):
        key = 'home:nav:list'
        navList = cache.get(key)
        if navList:
            return Response({
                'code': 200,
                'msg': '请求成功',
                'data': navList
            })
        navlist = models.Nav.objects.filter(is_del=False, is_show=True).order_by('sort')
        res = ser.NavSerializer(navlist, many=True)
        if not res.data:
            cache.set(key, [], 60 * 60 * 24)
        cache.set(key, res.data, 60 * 60 * 24)
        return Response({
            'code': 200,
            'msg': '请求成功',
            'data': res.data
        })


class CategoryList(APIView):
    def get(self, request):
        key = 'home:category:list'
        categoryList = cache.get(key)
        if categoryList:
            return Response({
                'code': 200,
                'msg': '请求成功',
                'data': categoryList
            })
        categorylist = models.Category.objects.filter(is_del=False, is_show=True, parent=None).order_by('sort')
        res = ser.CategorySerializer(categorylist, many=True)
        if not res.data:
            cache.set(key, [], 60 * 60 * 24)
        cache.set(key, res.data, 60 * 60 * 24)
        return Response({
            'code': 200,
            'msg': '请求成功',
            'data': res.data
        })


class Banner(APIView):
    def get(self, request):
        key = 'home:banner:list'
        bannerList = cache.get(key)
        if bannerList:
            return Response({
                'code': 200,
                'msg': '请求成功',
                'data': bannerList
            })
        bannerlist = models.Banner.objects.filter(is_del=False, is_show=True).order_by('sort')
        res = ser.BannerSerializer(bannerlist, many=True)
        if not res.data:
            cache.set(key, [], 60 * 60 * 24)
        cache.set(key, res.data, 60 * 60 * 24)
        return Response({
            'code': 200,
            'msg': '请求成功',
            'data': res.data
        })


# 调用异步任务
class SendEmail(APIView):
    def post(self, request):
        # 异步函数调用 如果有参数在delay传递
        result = send_mail.delay('3181444897@qq.com', "测试邮件")
        # 打印任务id
        # print(result.id)
        return Response({"code": 200, "msg": "ok"})
